package com.fbs.wowo.wx.service;

import com.fbs.wowo.exception.DataOverflowException;
import com.fbs.wowo.exception.ErrorCode;
import com.fbs.wowo.wx.entity.WxEntity;
import com.fbs.wowo.wx.mapper.WxEntityMapper;
import com.fbs.wowo.wx.web.TicketController;
import com.fbs.wowo.wx.wxUtil.HttpUtils;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

@Service
public class AccessTokenService {

    @Resource
    private WxEntityMapper wxEntityMapper;

    public String getWxAccessToken() {
        WxEntity wx = wxEntityMapper.selectByPrimaryKey(1);
        if (wx != null) {
            if (wx.getComAccessTokenExpirationTime() != null && !wx.getComAccessTokenExpirationTime().equals("")) {
                if (System.currentTimeMillis() < wx.getComAccessTokenExpirationTime()) {
                    if (wx.getComAccessToken() != null && !wx.getComAccessToken().equals("")) {
                        return wx.getComAccessToken();
                    }
                }
            }
            String url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";
            HashMap<String, String> map = new HashMap<>();
            map.put("component_appid", TicketController.appId);
            map.put("component_appsecret", TicketController.appSecret);
            if (wx.getTicket()!=null && !wx.getTicket().equals("")){
                map.put("component_verify_ticket", wx.getTicket());
                JSONObject jsonParam = JSONObject.fromObject(map);
                String returnData = HttpUtils.post(url, jsonParam.toString());
                System.out.println("getAccessToken:\n"+returnData+"\n\n");
                JSONObject json = JSONObject.fromObject(returnData);
                if (json.containsKey("component_access_token")) {
                    if (json.get("component_access_token") != null && !json.get("component_access_token").equals("")) {
                        wx.setComAccessTokenExpirationTime(System.currentTimeMillis() + (Integer.parseInt(json.get("expires_in").toString())*1000));
                        wx.setComAccessToken(json.get("component_access_token").toString());
                        wxEntityMapper.updateByPrimaryKeySelective(wx);
                        return json.get("component_access_token").toString();
                    }
                }
                throw new DataOverflowException(ErrorCode.ERR_ACCESS_TOKEN_NULL);
            }
            throw new DataOverflowException(ErrorCode.ERR_TICKET_NULL);
        }
        throw new DataOverflowException(ErrorCode.ERR_WXENTITY_NULL);
    }
}
